package controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pojo.SysRole;
import pojo.SysUser;
import service.SysRoleService;
import utils.Constants;

import jakarta.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/role")
public class SysRoleController {
    private Logger log=Logger.getLogger(SysRoleController.class);
    @Resource(name = "sysRoleService")
    private SysRoleService sysRoleService;

    @GetMapping("/sysRoleList")
    public String sysRoleList(HttpServletRequest request){
        List<SysRole> roleList = sysRoleService.getRoleList();
        request.setAttribute("roleList",roleList);
        return "sysRole/list";
    }

    @ResponseBody
    @GetMapping("/simpleList")
    public Object simpleList(){
        System.out.println("获取角色列表--------");
        return sysRoleService.getRoleList();
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        return "sysRole/add";
    }

    @PostMapping("/add")
    public String add(SysRole sysRole){
        boolean add = sysRoleService.add(sysRole);
        if(!add){
            return "redirect:/sys/role/toAdd";
        }
        return "redirect:/sys/role/sysRoleList";
    }

    @GetMapping("/toUpdate/{roleid}")
    public String toUpdate(@PathVariable Integer roleid, Model model){
        SysRole sysRole = sysRoleService.getRoleById(roleid);
        model.addAttribute("sysRole",sysRole);
        return "sysRole/update";
    }

    @PostMapping("/update")
    public String update(SysRole sysRole, HttpSession session){
        System.out.println("更新角色信息："+sysRole);
        SysUser user= (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysRole.setUpdatedUserId((long) user.getId());
        sysRole.setUpdatedTime(new Date());
        boolean update = sysRoleService.update(sysRole);
        log.debug("更新结果："+update);
        if(!update){
            return "sysRole/update";
        }
        return "redirect:/sys/role/sysRoleList";
    }

    @DeleteMapping("/del/{roleid}")
    @ResponseBody
    public Object del(@PathVariable Integer roleid){
        log.debug("删除角色："+roleid);
        Map<String,Object> map = new HashMap<String,Object>();
        boolean del = sysRoleService.delete(roleid);
        log.debug("删除结果："+del);
        map.put("delResult",del?"true":"false");
        return map;
    }
}
